package com.mycp.splashlib

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebView
import android.webkit.WebViewClient
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.gyf.immersionbar.ImmersionBar
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.xzkj.sp.SpUtils
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.MalformedURLException
import java.net.URL
import kotlin.system.exitProcess


class PrivacyPolicyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (layoutRes != 0) {
            setContentView(layoutRes)
            ImmersionBar.with(this).init()
        }
        val title = bundle?.getString("title")
        val content = bundle?.getString("content")
        val umengAppKey = bundle?.getString("umengAppKey")
        val umengChanel = bundle?.getString("umengChanel")

        showDialog(this, title, content, umengAppKey, umengChanel)
    }


    private fun showDialog(
        context: Context,
        title: String?,
        content: CharSequence?,
        umengAppKey: String?,
        umengChanel: String?
    ) {
        MaterialDialog(context).cancelable(false).cancelOnTouchOutside(false).show {
            title(text = title)
//            message(text = content)
            customView(R.layout.privacy_dialog_webview, horizontalPadding = true)
            positiveButton(text = "同意") { _ ->
                dismiss()
                //通知APP，隐私协议已经同意。可以初始化sdk了。
                SpUtils.put(this@PrivacyPolicyActivity, "sp_privacy_policy_agree", 1)

                //友盟正式初始化
                UMConfigure.init(
                    this@PrivacyPolicyActivity,
                    umengAppKey,
                    umengChanel,
                    UMConfigure.DEVICE_TYPE_PHONE,
                    null
                )
                // 选用AUTO页面采集模式
                // 选用AUTO页面采集模式
                MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
                privacyCall?.call()
                startIntent()
            }
            negativeButton(text = "不同意退出") {
                dismiss()
                finish()
                exitProcess(0)
            }
            val webView = this.findViewById<WebView>(R.id.webview)
            webView!!.loadDataWithBaseURL(
                null,
                setWebVIewImage(content.toString()),
                "text/html",
                "utf-8",
                null
            )
            webView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    if (url != null) {
                        CommonWebViewActivity.intentStart(getContext(), "", url)
                    }
                    return true
                }

            }
        }
    }


    companion object {
        private var bundle: Bundle? = null
        private var clazzString: String = ""
        private var clazz: Class<*>? = null
        private var layoutRes: Int = 0

        private var privacyCall : PrivacyCall? = null

        /**
         * 点击同意之后回调
         * @param call PrivacyCall
         */
        fun setPrivacyCall(call: PrivacyCall) {
            privacyCall = call
        }

        /**
         * className点击同意跳转的界面，bundle1，需要传给className的数据, layoutRes1 背景布局
         */
        fun start(context: Context, bundle1: Bundle) {
            bundle = bundle1
            clazzString = bundle1.getString("className").toString()
            layoutRes = bundle1.getInt("layoutRes")
            clazz = Class.forName(clazzString)
            val intent = Intent(context, PrivacyPolicyActivity::class.java)
            intent.putExtras(bundle!!)
            context.startActivity(intent)
        }

        // 适配image和table标签
        fun setWebVIewImage(star: String): String {
            val head = ("<head>"
                    + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                    + "<style>img{max-width: 100%; width:auto; height:auto;}</style>"
                    + "<style>table{max-width: 100%; width:auto; height:auto;}</style>"
                    + "</head>")
            return "<html>$head<body>$star</body></html>"
        }

        /**
         * 读取网页全部内容
         */
        fun getHtmlContent(htmlurl: String?): String {
            val url: URL
            var temp: String?
            val sb = StringBuffer()
            try {
                url = URL(htmlurl)
                val bufferedReader =
                    BufferedReader(InputStreamReader(url.openStream(), "utf-8")) // 读取网页全部内容
                while (bufferedReader.readLine().also { temp = it } != null) {
                    sb.append(temp)
                }
                bufferedReader.close()
            } catch (me: MalformedURLException) {
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return sb.toString()
        }
    }

    private fun startIntent() {
        val intent = Intent()
        intent.setClass(this, clazz!!)
        intent.putExtras(bundle!!)
        startActivity(intent)
        finish()
    }

}